﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using PaymentHelper.Core.RelatedObject;
using PaymentHelper.Core.ExceptionHandler;
using PaymentHelper.Core.MultiLanguage;

namespace PaymentHelper.Core.Extension
{
    public class ExtensionDescriptor
    {
        public string SystemName { get; set; }

        public string FriendlyName { get; set; }

        public string Author { get; set; }

        public string Version { get; set; }

        public string Description { get; set; }

        public bool Installed { get; set; }

        public bool Enable { get; set; }

        public Type TypeExtension { get; set; }

        public Assembly ReferencedAssembly { get; set; }

        public LanguageContainer LanguageContainer { get; set; }

        public T GetInstance<T>() where T:class,IExtension
        {
            object instance = null;

            try
            {
                instance = Activator.CreateInstance(TypeExtension);

                if (instance == null)
                    return null;

                var realInstance = instance as T;
                if(realInstance != null)
                    realInstance.Descriptor = this;

                return realInstance;
            }
            catch(Exception e)
            {
                throw new PaymentHelperException(ExceptionLevel.Error, "ExtensionDescriptor.GetInstance", "Can't create an instance of extension", e);
            }            
        }

        public void LoadTypeExtension()
        {
            try
            {

                if (ReferencedAssembly != null)
                {
                    TypeExtension = ReferencedAssembly.GetTypes().Where(t => typeof(IExtension).IsAssignableFrom(t)
                                        && !t.IsAbstract && !t.IsAbstract && t.IsClass).FirstOrDefault();
                }
            }
            catch (ReflectionTypeLoadException e)
            {
                throw e;
            }
        }

        public LanguagePackage GetDefaultLanguage()
        {
            return LanguageContainer.GetDefaultLanguagePackage();
        }

        public LanguagePackage GetLanguage(string key)
        {
            return LanguageContainer[key];
        }

        public override string ToString()
        {
            return FriendlyName;
        }
    }
}
